﻿using AutoMapper;
using HuiLian.Common.Helpers;
using HuiLian.Common.Input;
using HuiLian.Common.Output;
using HuiLian.Model.Platform;
using HuiLian.Repository.Platform;
using HuiLian.Repository.Platform.PipeSurvivalTime;
using HuiLian.Service.Platform.PipeHealth;
using HuiLian.Service.Platform.PipeSurvivalTime.Output;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static FreeSql.Internal.GlobalFilter;

namespace HuiLian.Service.Platform.PipeSurvivalTime
{
    public class PipeSurvivalTimeService : IPipeSurvivalTimeService
    {
        private readonly IMapper _mapper;
        private readonly IPipeSurvivalTimeRepository _pipeSurvivalTimeRepository;
        private readonly IPipeRepository _pipeRepository;

        public PipeSurvivalTimeService(
            IMapper mapper,
            IPipeSurvivalTimeRepository pipeSurvivalTimeRepository,
            IPipeRepository pipeRepository)
        {
            _mapper = mapper;
            _pipeSurvivalTimeRepository = pipeSurvivalTimeRepository;
            _pipeRepository = pipeRepository;
        }

        /// <summary>
        /// 获取管网资产信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public async Task<IResponseOutput> GetAsync(long id)
        {
            var data = await _pipeRepository.Select.Where(p => p.Id == id).FirstAsync();
            if (data == null) return ResponseOutput.NotOk("不存在");
            PipeSurvivalTimeGetOutput output = _mapper.Map<PipeSurvivalTimeGetOutput>(data);
            PipeSurvivalTimeEntity pipeSurvivalTimeEntity = await _pipeSurvivalTimeRepository.Select.Where(p => p.PipeNum == data.管段编号).FirstAsync();
            if (pipeSurvivalTimeEntity != null)
            {
                output.SurvivalTime = pipeSurvivalTimeEntity.SurvivalTime;
                if (data.竣工接收时间 != null && !string.IsNullOrEmpty(pipeSurvivalTimeEntity.SurvivalTime))
                {
                    double time = Convert.ToDouble(pipeSurvivalTimeEntity.SurvivalTime);
                    time = time * 30;
                    output.预期破损时间 = output.竣工接收时间.Value.AddDays(time);
                }
            }
            
            return ResponseOutput.Ok(output);
        }

        /// <summary>
        /// 查询管网资产信息
        /// </summary>
        /// <param name="input">分页信息</param>
        /// <returns></returns>
        public async Task<IResponseOutput<PageOutput<PipeSurvivalTimeListOutput>>> PageAsync(PageInput<PipeEntity> input)
        {
            var res = new ResponseOutput<PageOutput<PipeSurvivalTimeListOutput>>();

            try
            {
                //var key = input.Filter?.Label;

                var list = await _pipeRepository.Select
                .WhereDynamicFilter(input.DynamicFilter)
                //.WhereIf(key.NotNull(), a => a.Path.Contains(key) || a.Label.Contains(key))
                .Count(out var total)
                .OrderBy(true, c => c.Id)
                .Page(input.CurrentPage, input.PageSize)
                .ToListAsync();

                List<PipeSurvivalTimeListOutput> pipeSurvivalTimeListOutputs = _mapper.Map<List<PipeSurvivalTimeListOutput>>(list);
                var pipeNumList = list.Select(p => p.管段编号).ToList();
                var pipeSurvivalTimeEntityList = await _pipeSurvivalTimeRepository.Select.Where(p => pipeNumList.Contains(p.PipeNum)).ToListAsync();
                if(pipeSurvivalTimeListOutputs != null && pipeSurvivalTimeEntityList != null)
                {
                    foreach (var item in pipeSurvivalTimeListOutputs)
                    {
                        var pipeSurvivalTime = pipeSurvivalTimeEntityList.Where(p => p.PipeNum == item.管段编号).FirstOrDefault();
                        if (pipeSurvivalTime != null) item.SurvivalTime = pipeSurvivalTime.SurvivalTime;
                        else item.SurvivalTime = "无";
                        if(item.竣工接收时间 != null && pipeSurvivalTime != null && !string.IsNullOrEmpty(pipeSurvivalTime.SurvivalTime))
                        {
                            double time = Convert.ToDouble(pipeSurvivalTime.SurvivalTime);
                            time = time * 30;
                            item.预期破损时间 = item.竣工接收时间.Value.AddDays(time);
                        }
                    }
                }

                var data = new PageOutput<PipeSurvivalTimeListOutput>()
                {
                    List = pipeSurvivalTimeListOutputs,
                    Total = total
                };

                return res.Ok(data);
            }
            catch (Exception ex) { return res.NotOk(ex.Message + " " + ex.StackTrace); }
        }

        /// <summary>
        /// 查询分页模型结果
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> UpdateTime(PageInput<PipeEntity> input)
        {
            long total = 0;
            input.CurrentPage = 0;
            input.PageSize = 10000;
            do
            {
                input.CurrentPage++;                

                var pointResult = await PageAsync(input);
                if (pointResult.Success)
                {
                    total = pointResult.Data.Total;
                    //points.AddRange(pointResult.Data.List.AsEnumerable());
                    List<PipeSurvivalTimeEntity> list = _mapper.Map<List<PipeSurvivalTimeEntity>>(pointResult.Data.List);
                    foreach (var item in list)
                    {
                        if (item.SurvivalTime == "无") item.SurvivalTime = "";
                    }
                    var bn = list.Select(p => p.PipeNum).ToList();
                    var enlist = await _pipeSurvivalTimeRepository.Select.Where(p => bn.Contains(p.PipeNum)).ToListAsync();
                    //_mapper.Map(list, enlist);
                    foreach (var item in enlist)
                    {
                        var e = list.Where(p => p.PipeNum == item.PipeNum).FirstOrDefault();
                        if(e != null)
                        {
                            item.预期破损时间 = e.预期破损时间;
                        }
                    }
                    await _pipeSurvivalTimeRepository.UpdateAsync(enlist);
                    Console.WriteLine(input.PageSize * input.CurrentPage);
                }
                else
                {
                    return ResponseOutput.NotOk("导出失败");
                }
            }
            while (input.PageSize * input.CurrentPage < total);
            return ResponseOutput.Ok(true);
        }
    }
}
